const express = require("express");
const router = express.Router();
//引入cookie
// var cookieParser = require("cookie-parser");
// 引入数据库模块
var MongoClient = require("mongodb").MongoClient;
let objectId = require("mongodb").ObjectId;
let url = "mongodb://localhost:27017/"; //多用户
// 封装连接数据库的方法
function getDb(callback) {
  MongoClient.connect(url, (err, db) => {
    callback(err, db);
  });
}
// 引入表单模块
var multiparty = require("multiparty");
// 引入fs文件处理模块
let fs = require("fs");
// 通用
router.get("/ip", (req, res) => {
  fs.readFile("./router/ip.txt", "utf-8", (err, data) => {
    // console.log(err);
    //null 没有错误
    // console.log(data);
    //不存在自动创建文件
    if (err) {
      return res.json({ status: -1, info: "配置文件丢失！" });
    } else {
      return res.json({ status: 1, info: "配置文件获取成功！", data: data });
    }
  });
});
//获取客户端ip
//通过req的hearers来获取客户端ip
var getIp = function (req) {
  var ip =
    req.headers["x-real-ip"] ||
    req.headers["x-forwarded-for"] ||
    req.connection.remoteAddres ||
    req.socket.remoteAddress ||
    "";
  if (ip.split(",").length > 0) {
    ip = ip.split(",")[0];
  }
  return ip;
};
// 获取客户端ip地址
router.get("/getIp", (req, res) => {
  var clientIp = getIp(req);
  res.json({ userIp: clientIp });
});

// 选择数据库
const sDb = function (db, dbname) {
  // return db.collection("user");
  return db.db(dbname);
};
// superSet
router.post("/superSet", (req, res) => {
  // console.log(req.body.value);
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      // dbo.collection("superAdmin").find().count();
      dbo
        .collection("superAdmin")
        .find({})
        .toArray()
        .then((count) => {
          // console.log(count.length == 1);
          // 如果数据库中没有数据，则插入数据
          if (count.length < 1) {
            dbo
              .collection("superAdmin")
              .insertOne(req.body.value, (error, result) => {
                return res.json({ status: 1, msg: "初始化成功" });
              });
          } else {
            // console.log(count[0]._id);
            let _id = count[0]._id;
            dbo
              .collection("superAdmin")
              .updateOne({ _id }, { $set: req.body.value }, (error, result) => {
                return res.json({ status: 1, msg: "更新成功" });
              });
            // dbo
            //   .collection("superAdmin")
            //   .insertOne(req.body.value, (error, result) => {
            //     console.log(error);
            //   });
          }
        });
    }
  });
});
// superGet
router.get("/superGet", (req, res) => {
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      dbo
        .collection("superAdmin")
        .find()
        .toArray((err, data) => {
          // console.log(data.length);
          if (data.length < 1) {
            // 无数据
            return res.json({ status: 0, msg: "暂无数据" });
          } else {
            // 有数据
            return res.json({ status: 1, msg: "获取成功", data: data });
          }
        });
    }
  });
});
// 手机端
// var https = require("https");
const request = require("request");
let title = encodeURI("用户注册提醒");
let moment = require("moment");
// 注册
router.post("/Register", (req, res) => {
  // console.log(req.body);
  // return
  getDb((err, db) => {
    // sDb(db,"HJSYS")
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      //   查询数据库中是否有该用户
      dbo
        .collection("UAdmin")
        .find({ UAdminPhone: req.body.UAdminPhone })
        .toArray((err, data) => {
          if (err) {
            return res.json({ status: -10, msg: "数据库查询失败" });
          } else {
            if (data.length > 0) {
              return res.json({ status: -1, msg: "用户名已存在" });
            } else {
              // 插入数据
              dbo.collection("UAdmin").insertOne(req.body, (err, data) => {
                if (err) {
                  return res.json({ status: 0, msg: "数据库插入失败" });
                } else {
                  // server推送
                  var postData = {
                    手机号: req.body.UAdminPhone,
                    所属网点: req.body.StoreName,
                    注册时间: moment(Date.now()).format("YYYY-MM-DD HH:mm:ss"),
                  };
                  const server =
                    "https://sctapi.ftqq.com/SCT23686T61dEHILWw0zrOGDHn0UW5Dh2.send?title=" +
                    title +
                    "&desp=" +
                    encodeURI(JSON.stringify(postData));
                  request({
                    url: server,
                    method: "POST",
                    json: true,
                    headers: {
                      "Content-Type": "application/x-www-form-urlencoded",
                    },
                  });
                  fs.access("static/upload/" + data, (err) => {
                    //检测文件夹是否存在
                    if (err) {
                      fs.mkdir(
                        "static/upload/" + req.body.EStoreName,
                        function (err) {
                          if (err) {
                            return err;
                          }
                        }
                      );
                    }
                  });
                  return res.json({ status: 1, msg: "注册成功" });
                }
              });
            }
          }
        });
    }
  });
});
// 登陆
router.post("/Login", (req, res) => {
  // console.log(req.body);
  //   let _id = objectId(req.body.UAdminPhone);
  //   console.log(_id);
  // return;
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      dbo
        .collection("UAdmin")
        .find({ UAdminPhone: req.body.UAdminPhone })
        .toArray((err, data) => {
          if (err) {
            return res.json({ status: -10, msg: "数据库查询失败" });
          } else {
            if (data.length <= 0) {
              return res.json({ status: -1, msg: "用户名不存在" });
            } else if (
              !data[0].mServer &&
              !data[0].isAdmin &&
              req.body.type_ == "mobile"
            ) {
              return res.json({ status: -2, msg: "该用户未启用(移动端)" });
            } else if (
              !data[0].pcServer &&
              !data[0].isAdmin &&
              req.body.type_ == "pc"
            ) {
              return res.json({ status: -3, msg: "该用户未启用(pc端)" });
            } else if (req.body.UAdminPwd != data[0].UAdminPwd) {
              return res.json({ status: -4, msg: "密码错误" });
            } else {
              // console.log(data[0].isAdmin);
              if (data[0].isAdmin) {
                return res.json({ status: 10, msg: "admin" });
              } else {
                return res.json({
                  status: 1,
                  data: data,
                  msg: "登陆成功",
                });
              }
            }
          }
        });
    }
  });
});
// 获取所有管理用户
router.get("/getAdminAllUser", (req, res) => {
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      dbo
        .collection("UAdmin")
        .find({})
        .toArray((err, data) => {
          if (err) {
            return res.json({ status: -10, msg: "数据库查询失败" });
          } else {
            return res.json({ status: 1, data: data, msg: "数据查询成功" });
          }
        });
    }
  });
});
// 获取单个管理用户
router.post("/getAdminUser", (req, res) => {
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      // console.log(req.body._id);
      // console.log(res);
      dbo
        .collection("UAdmin")
        .find({ _id: objectId(req.body._id) })
        .toArray((err, data) => {
          // console.log(data);
          if (err) {
            return res.json({ status: -10, msg: "数据库查询失败" });
          } else {
            return res.json({ status: 1, data: data, msg: "数据查询成功" });
          }
        });
    }
  });
});
// 管理员自行修改密码
router.post("/editAdminPwd", (req, res) => {
  let UAdminPhone = req.body.phone;
  let UAdminPwd = req.body.passwd;
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      dbo
        .collection("UAdmin")
        .updateOne(
          { UAdminPhone },
          { $set: { UAdminPwd: UAdminPwd } },
          (err, data) => {
            // console.log(err);
            if (err) {
              return res.json({ status: -10, msg: "数据库查询失败" });
            } else {
              return res.json({ status: 1, msg: "修改成功" });
            }
          }
        );
    }
  });
});
// 修改管理用户
router.post("/updateAdminUser", (req, res) => {
  let _id = objectId(req.body._id);
  delete req.body._id;
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      dbo
        .collection("UAdmin")
        .updateOne({ _id }, { $set: req.body }, (err, data) => {
          // console.log(err);
          if (err) {
            return res.json({ status: -10, msg: "数据库查询失败" });
          } else {
            return res.json({ status: 1, msg: "更新成功" });
          }
        });
    }
  });
});
// 删除管理用户
router.get("/deleteAdminUser", (req, res) => {
  // console.log(req.query._id);
  let _id = objectId(req.query._id);
  // delete req.body._id;
  // console.log(_id);
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      dbo.collection("UAdmin").deleteOne({ _id }, (err, data) => {
        if (err) {
          return res.json({ status: -10, msg: "数据库查询失败" });
        } else {
          return res.json({ status: 1, msg: "删除成功" });
        }
      });
    }
  });
});
// 客户信息管理

// 获取店铺名简称
function getFromName(LoginInfo) {
  // console.log(LoginInfo); //
  return new Promise(function (resolve) {
    getDb((err, db) => {
      const dbo = sDb(db, "HJSYS");
      dbo
        .collection("UAdmin")
        .findOne({ UAdminPhone: LoginInfo }, (err, data) => {
          // return data.EStoreName;
          resolve(data.EStoreName);
        });
    });
  });
}
var mv = require("mv");
function reImg(imgPath, EStoreName) {
  // return
  // return;
  if (imgPath != undefined) {
    // console.log(imgPath[0].path.slice(imgPath[0].path.lastIndexOf("\\") + 1));
    let oldImgPath = imgPath[0].path.replace(/\\/g, "/");

    // let newImpPath =
    //   EStoreName +
    //   "/" +
    //   imgPath[0].path.slice(imgPath[0].path.lastIndexOf("\\") + 1);
    imgPath =
      "static/upload/" +
      EStoreName +
      "/" +
      // imgPath[0].path.slice(imgPath[0].path.lastIndexOf("\\") + 1);
    imgPath[0].path.slice(imgPath[0].path.lastIndexOf("\/") + 1);

    mv(oldImgPath, imgPath, function (err) {});
    // console.log(oldImgPath + "-------------");
    // console.log(v)
  } else {
    imgPath = null;
  }
  return imgPath;
}
// 新增客户信息
router.post("/addCustomer", (req, res) => {
  let form = new multiparty.Form();
  // getFromName(form);

  // console.log(getFromName(req, form));
  // 创建文件夹 data;
  // console.log(data + "888");
  form.uploadDir = "static/upload/";
  // console.log(form);
  // return;
  // var req_ = req;
  // console.log(req_);
  // let form_ = new multiparty.Form();
  form.parse(req, (err, fields, files) => {
    // console.log(fields.address != undefined);
    // console.log(fields.EStoreName[0]);
    // return false;
    // console.log(fields.LoginInfo[0]);
    getFromName(fields.LoginInfo[0]).then((table) => {
      // console.log(fields);
      // reImg(files.img, fields.EStoreName[0]);
      // return;
      // reImg(files.img, fields.EStoreName[0]);
      // console.log(reImg(files.img, fields.EStoreName[0]));
      // return;
      // console.log(fields.code_sc == undefined);
      // return;
      let insertData = {
        username: fields.username[0], //姓名
        call: fields.call[0], //电话
        sfz: fields.sfz != undefined ? fields.sfz[0] : "", //身份证
        birthday: fields.birthday != undefined ? fields.sfz[0] : "", //生日
        sex: fields.sex != undefined ? fields.sex[0] : "", //性别
        address: fields.address != undefined ? fields.address[0] : "", //地址
        buy: fields.buy != undefined ? fields.buy[0] : false, //是否购车
        newMoto: fields.newMoto != undefined ? fields.newMoto[0] : false, //是否新车
        date1: fields.date1 != undefined ? fields.date1[0] : "", //购车日期
        Moto: fields.Moto != undefined ? fields.Moto[0] : "", //购车品牌
        MotoType: fields.MotoType != undefined ? fields.MotoType[0] : "", //车辆型号
        brand: fields.brand != undefined ? fields.brand[0] : "", //车牌号
        bx_true: fields.bx_true != undefined ? fields.bx_true[0] : false, //是否有保险
        date: fields.date != undefined ? fields.date[0] : "", //保险购买日期
        sc_true: fields.sc_true != undefined ? fields.sc_true[0] : false, //是否审车
        date_sc: fields.date_sc != undefined ? fields.date_sc[0] : "", //审车日期
        date_jsz: fields.date_jsz != undefined ? fields.date_jsz[0] : "", //驾驶证日期
        img: reImg(files.img, fields.EStoreName[0]), // 行驶证
        img_xszfm: reImg(files.img_xszfm, fields.EStoreName[0]), // 行驶证反面
        img_qs: reImg(files.img_qs, fields.EStoreName[0]), //合格证
        img_new: reImg(files.img_new, fields.EStoreName[0]), //新车合照
        img_jsz: reImg(files.img_jsz, fields.EStoreName[0]), //驾驶证
        code:
          fields.code != undefined || fields.code != null ? fields.code[0] : "", // 排序用
        code_sc:
          fields.code_sc != undefined || fields.code_sc != null
            ? fields.code_sc[0]
            : "", // 忘了
        desc: fields.desc != undefined ? fields.desc[0] : "", // 备注
      };
      // return false;
      getDb((err, db) => {
        const dbo = sDb(db, "HJSYS");
        if (err) {
          return res.json({ status: -20, msg: "数据库连接失败" });
        } else {
          dbo.collection(table).insertOne(insertData, (error, result) => {
            if (error) {
              return res.json({ status: 0, msg: "数据库插入失败" });
            } else {
              fields = {};
              return res.json({ status: 1, msg: "添加成功" });
            }
          });
        }
      });
    });
  });
});
// 所有用户信息
router.post("/getAlluser", (req, res) => {
  // console.log(req.body);
  // return
  getFromName(req.body.LoginInfo).then((data) => {
    // console.log(data);
    // return
    getDb((err, db) => {
      const dbo = sDb(db, "HJSYS");
      if (err) {
        return res.json({ status: -20, msg: "数据库连接失败" });
      } else {
        // dbo.collection("UAdmin").find({}).toArray((err, data) => {
        dbo
          .collection(data)
          .find({})
          .toArray((err, result) => {
            if (err) {
              return res.json({ status: -10, msg: "数据库查询失败" });
            } else {
              return res.json({ status: 1, data: result, msg: "数据查询成功" });
            }
          });
      }
    });
  });
});
//单个用户信息
router.post("/getOneUser", (req, res) => {
  // console.log(req.body);
  // let id = ObjectID()
  let _id = objectId(req.body._id);
  getFromName(req.body.LoginInfo).then((data) => {
    getDb((err, db) => {
      const dbo = sDb(db, "HJSYS");
      if (err) {
        return res.json({ status: -20, msg: "数据库连接失败" });
      } else {
        // console.log(_id);
        // console.log(res);
        dbo
          .collection(data)
          .find(_id)
          .toArray((err, result) => {
            // console.log(result);
            if (err) {
              return res.json({ status: -10, msg: "数据库查询失败" });
            } else {
              return res.json({ status: 1, data: result, msg: "数据查询成功" });
            }
          });
      }
    });
  });
});
// 查询
router.post("/Search", (req, res) => {
  // console.log(req.body);
  // return;
  let reg = new RegExp(req.body.info);
  getFromName(req.body.LoginInfo).then((data) => {
    // console.log(data);
    getDb((err, db) => {
      const dbo = sDb(db, "HJSYS");
      dbo
        .collection(data)
        .find({
          $or: [
            { username: reg },
            { address: reg },
            { call: reg },
            { MotoType: reg },
            { date1: reg },
          ],
        })
        .toArray((error, result) => {
          // console.log(result);
          if (error) {
            return res.json({ status: -10, msg: "数据库查询失败" });
          } else {
            return res.json({ status: 1, data: result, msg: "查找成功" });
            // return res.json({ status: 1, info: "查找成功", data: result });
          }
        });
    });
  });
});
// 判断是否修改图片
function updateReImg(fields, files, name, EStoreName) {
  // console.group(fields);
  // console.groupEnd("---------------------------------");
  // console.group(files);
  // console.groupEnd("---------------------------------");
  // console.log(fields);
  // 修改了 === [object Object]   未修改 !==[object Object]   || ===""
  // console.log(fields+"files");
  // console.log(name+"name");

  //未修改
  // console.log(fields["old" + name][0]);
  // console.log(files[name] == undefined);
  if (fields["old" + name][0] == "" && files[name] == undefined) {
    // console.log("未修改无图");
    return "";
  } else if (fields["old" + name][0] != "" && files[name] == undefined) {
    // console.log("未修改保留原图");
    // console.log(
    //   "static/upload/" +
    //     EStoreName +
    //     fields["old" + name][0].slice(fields["old" + name][0].lastIndexOf("/"))
    // );
    // static/upload/ZDUZPpbhkVOg2GkNRriLcgPA.png
    // return;
    return (
      "static/upload/" +
      EStoreName +
      fields["old" + name][0].slice(fields["old" + name][0].lastIndexOf("/"))
    );
  } else if (files[name] != undefined) {
    if (fields["old" + name][0] != "") {
      fs.unlink(
        "./static/upload/" +
          EStoreName +
          "/" +
          fields["old" + name][0].slice(
            fields["old" + name][0].lastIndexOf("/")
          ),
        (err) => {
          // console.log(err);
        }
      );
    }
    // console.log(
    //   "static/upload/" +
    //     EStoreName +
    //     "/" +
    //     files[name][0].path.slice(files[name][0].path.lastIndexOf("\\") + 1)
    // );
    let oldImgPath = files[name][0].path.replace(/\\/g, "/");
    let newPath =
      "static/upload/" +
      EStoreName +
      "/" +
      files[name][0].path.slice(files[name][0].path.lastIndexOf("\/") + 1);
    // console.log("修改新图");
    mv(oldImgPath, newPath, function (err) {});
    return newPath;
  }
  return;
}
// 更新用户信息
router.post("/updateUser", (req, res) => {
  let form = new multiparty.Form();
  // getFromName(req, form);
  // console.log(getFromName(req, form));
  // 创建文件夹 data;
  // console.log(data + "888");
  form.uploadDir = "static/upload/";
  // var req_ = req;
  // console.log(req_);
  // let form_ = new multiparty.Form();
  form.parse(req, (err, fields, files) => {
    let _id = objectId(fields._id[0]);
    // console.group(fields);
    // console.group(fields);
    // console.group(files);
    // let img = if(){}
    // updateReImg(fields, files, "img");
    // updateReImg(fields, files, "img_xszfm");
    // return;

    // return;
    let insertData = {
      username: fields.username[0], //姓名
      call: fields.call[0], //电话
      sfz: fields.sfz != undefined ? fields.sfz[0] : "", //身份证
      birthday: fields.birthday != undefined ? fields.sfz[0] : "", //生日
      sex: fields.sex != undefined ? fields.sex[0] : "", //性别
      address: fields.address != undefined ? fields.address[0] : "", //地址
      buy: fields.buy != undefined ? fields.buy[0] : false, //是否购车
      newMoto: fields.newMoto != undefined ? fields.newMoto[0] : false, //是否新车
      date1: fields.date1 != undefined ? fields.date1[0] : "", //购车日期
      Moto: fields.Moto != undefined ? fields.Moto[0] : "", //购车品牌
      MotoType: fields.MotoType != undefined ? fields.MotoType[0] : "", //车辆型号
      brand: fields.brand != undefined ? fields.brand[0] : "", //车牌号
      bx_true: fields.bx_true != undefined ? fields.bx_true[0] : false, //是否有保险
      date: fields.date != undefined ? fields.date[0] : "", //保险购买日期
      sc_true: fields.sc_true != undefined ? fields.sc_true[0] : false, //是否审车
      date_sc: fields.date_sc != undefined ? fields.date_sc[0] : "", //审车日期
      date_jsz: fields.date_jsz != undefined ? fields.date_jsz[0] : "", //驾驶证日期
      img: updateReImg(fields, files, "img", fields.EStoreName[0]), // 行驶证
      img_xszfm: updateReImg(fields, files, "img_xszfm", fields.EStoreName[0]), // 行驶证反面
      img_qs: updateReImg(fields, files, "img_qs", fields.EStoreName[0]), //合格证
      img_new: updateReImg(fields, files, "img_new", fields.EStoreName[0]), //新车合照
      img_jsz: updateReImg(fields, files, "img_jsz", fields.EStoreName[0]), //驾驶证
      // img_new: reImg(files.img_new), //新车合照
      // img_jsz: reImg(files.img_jsz), //驾驶证
      code: fields.code != undefined ? fields.code[0] : "", // 排序用
      code_sc: fields.code_sc != undefined ? fields.code_sc[0] : "", // 忘了
      desc: fields.desc != undefined ? fields.desc[0] : "", // 备注
    };
    // console.log(insertData);
    getFromName(fields.LoginInfo[0]).then((data) => {
      getDb((err, db) => {
        const dbo = sDb(db, "HJSYS");
        if (err) {
          return res.json({ status: -20, msg: "数据库连接失败" });
        } else {
          dbo
            .collection(data)
            .updateOne({ _id }, { $set: insertData }, (err, data) => {
              // console.log(_id);
              if (err) {
                return res.json({ status: -10, msg: "数据库查询失败" });
              } else {
                return res.json({ status: 1, msg: "更新成功" });
              }
            });
        }
      });
    });
  });
  // });
});
function oldImg(fields, name) {
  if (fields[name] != "") {
    return fields[name][0].slice(fields[name][0].lastIndexOf("/"));
  }
}
router.post("/deleteUser", (req, res) => {
  let form = new multiparty.Form();
  form.parse(req, (err, fields, files) => {
    let _id = objectId(fields._id[0]);
    // return;
    // console.log(fields);
    let EStoreName = fields.EStoreName[0];
    getFromName(fields.LoginInfo[0]).then((data) => {
      // console.log(data);
      getDb((err, db) => {
        const dbo = sDb(db, "HJSYS");
        if (err) {
          return res.json({ status: -20, msg: "数据库连接失败" });
        } else {
          dbo.collection(data).deleteOne({ _id }, (err, result) => {
            // console.log(_id);
            if (err) {
              return res.json({ status: -10, msg: "数据库查询失败" });
            } else {
              fs.unlink(
                "./static/upload/" +
                  EStoreName +
                  "/" +
                  oldImg(fields, "oldimg"),
                (err) => {}
              );
              fs.unlink(
                "./static/upload/" +
                  EStoreName +
                  "/" +
                  oldImg(fields, "oldimg_xszfm"),
                (err) => {}
              );
              fs.unlink(
                "./static/upload/" +
                  EStoreName +
                  "/" +
                  oldImg(fields, "oldimg_qs"),
                (err) => {}
              );
              fs.unlink(
                "./static/upload/" +
                  EStoreName +
                  "/" +
                  oldImg(fields, "oldimg_new"),
                (err) => {}
              );
              fs.unlink(
                "./static/upload/" +
                  EStoreName +
                  "/" +
                  oldImg(fields, "oldimg_jsz"),
                (err) => {}
              );
              return res.json({ status: 1, msg: "删除成功" });
            }
          });
        }
      });
    });
    return;
  });
});
// 电脑端移植
// 查询买保险当月的用户详细信息
router.post("/findbx", (req, res) => {
  // console.log(req.body)
  let code = req.body.date;
  getFromName(req.body.LoginInfo).then((data) => {
    getDb((err, db) => {
      const dbo = sDb(db, "HJSYS");
      dbo
        .collection(data)
        .find({ code })
        .toArray((error, result) => {
          return res.json({ status: 1, info: "获取成功", data: result });
        });
    });
  });
});
// 删除用户信息
router.post("/deluser", (req, res) => {
  // 获取基本参数(id)
  // console.log(req.body)
  let _id = objectId(req.body.id);
  // console.log();
  fs.unlink("./" + req.body.imgurl, (err) => {});
  fs.unlink("./static/" + req.body.imgurl, (err) => {});
  fs.unlink("./" + req.body.img_fm, (err) => {});
  fs.unlink("./static/" + req.body.img_fm, (err) => {});
  fs.unlink("./" + req.body.img_qs, (err) => {});
  fs.unlink("./static/" + req.body.img_qs, (err) => {});
  fs.unlink("./" + req.body.img_new, (err) => {});
  fs.unlink("./static/" + req.body.img_new, (err) => {});
  fs.unlink("./" + req.body.img_jsz, (err) => {});
  fs.unlink("./static/" + req.body.img_jsz, (err) => {});

  // 执行删除操作
  getFromName(req.body.LoginInfo).then((data) => {
    getDb((err, db) => {
      const dbo = sDb(db, "HJSYS");
      dbo.collection(data).deleteOne({ _id }, (error, result) => {
        if (error) {
          return res.json({ status: -1, info: "删除失败" });
        } else {
          return res.json({ status: 1, info: "删除成功" });
        }
      });
    });
  });
});
// 修改行驶证图片(pc版本)
router.post("/editimg", (req, res) => {
  // return;
  let form = new multiparty.Form();
  // 设置图片上传路径
  form.uploadDir = "static/upload";
  form.parse(req, (err, fields, files) => {
    // console.log(fields, files);
    // return;
    var tmpImgName = fields.imgName[0]; //标记修改的字段名
    let oldimg = fields.oldimg[0].slice(-35); //旧图地址
    // console.log(oldimg);
    // console.log(fields.oldimg[0]);
    // return 0;
    fs.unlink("./upload/" + oldimg, (err) => {
      // console.log(err);
    }); //删除旧图
    fs.unlink("./static/upload/" + oldimg, (err) => {
      // console.log(err);
    }); //删除旧图
    let imgPath = {};
    // console.log(files);
    // console.log(fields);
    // return 0;
    let imgTemp;
    let imgMv;
    if (JSON.stringify(files) == "{}") {
      imgTemp = fields[tmpImgName][0];
    } else {
      imgTemp = files[tmpImgName][0].path;
    }
    // img 图片路径    tmpImgName  索引名
    imgMv = "static/upload/" + imgTemp.substr(imgTemp.lastIndexOf("/") + 1);
    imgTemp =
      "static/upload/" +
      fields.E[0] +
      "/" +
      imgTemp.substr(imgTemp.lastIndexOf("/") + 1);
    // imgMv = "static/upload/" + imgTemp.substr(imgTemp.lastIndexOf("\\") + 1);
    // imgTemp =
    //   "static/upload/" +
    //   fields.E[0] +
    //   "/" +
    //   imgTemp.substr(imgTemp.lastIndexOf("\\") + 1);
    // console.log(imgTemp + "----390");
    // console.log(imgMv + "----400");
    mv(imgMv, imgTemp, function (err) {});
    // return 0;
    if (tmpImgName == "img") {
      let img = imgTemp;
      imgPath = { img };
    } else if (tmpImgName == "img_xszfm") {
      let img_xszfm = imgTemp;
      imgPath = { img_xszfm };
    } else if (tmpImgName == "img_qs") {
      let img_qs = imgTemp;
      imgPath = { img_qs };
    } else if (tmpImgName == "img_new") {
      let img_new = imgTemp;
      imgPath = { img_new };
    } else if (tmpImgName == "img_jsz") {
      let img_jsz = imgTemp;
      imgPath = { img_jsz };
    }
    // console.log(imgPath);
    // return false;
    let _id = objectId(fields._id[0]);
    getFromName(fields.LoginInfo[0]).then((data) => {
      getDb((err, db) => {
        const dbo = sDb(db, "HJSYS");
        dbo
          .collection(data)
          .updateOne({ _id }, { $set: imgPath }, (error, result) => {
            if (error) {
              return res.json({ status: -1, info: "修改失败" });
            } else {
              return res.json({ status: 1, info: "修改成功" });
            }
          });
      });
    });
  });
});
// 用户信息更新
router.post("/update", (req, res) => {
  // console.log(req.body.LoginInfo);
  // return;
  let _id = objectId(req.body._id);
  // console.log(_id)
  let username = req.body.username;
  let call = req.body.call;
  let address = req.body.address;
  let buy = req.body.buy;
  let newMoto = req.body.newMoto;
  let brand = req.body.brand;
  let sfz = req.body.sfz;
  let sex = req.body.sex;
  let birthday = req.body.birthday;
  if (sfz == "") {
    sex = "";
    birthday = "";
  }
  let date = req.body.date;
  let date1 = req.body.date1;
  let date_sc = req.body.date_sc;
  let Moto = req.body.Moto;
  let MotoType = req.body.MotoType;
  let Money = req.body.Money;
  let desc = req.body.desc;
  let towns = req.body.towns;
  let code = req.body.code;
  let code_sc = req.body.code_sc;
  let sc_true = req.body.sc_true;
  let bx_true = req.body.bx_true;

  let updateData = {
    $set: {
      username,
      call,
      address,
      buy,
      newMoto,
      sfz,
      sex,
      brand,
      birthday,
      date,
      date1,
      date_sc,
      Moto,
      MotoType,
      Money,
      desc,
      towns,
      code,
      code_sc,
      bx_true,
      sc_true,
    },
  };
  getFromName(req.body.LoginInfo).then((data) => {
    getDb((err, db) => {
      const dbo = sDb(db, "HJSYS");
      dbo.collection(data).updateOne({ _id }, updateData, (error, result) => {
        if (error) {
          return res.json({ status: -1, info: "修改失败" });
        } else {
          return res.json({ status: 1, info: "修改成功" });
        }
      });
    });
  });
});
// 获取短信剩余数量
router.post("/getMessageCount", (req, res) => {
  // console.log(req.body._id);
  let _id = objectId(req.body._id);
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      dbo.collection("UAdmin").findOne({ _id }, (error, result) => {
        // console.log(result.messagesQuantity);
        return res.json({ status: 1, data: result.messagesQuantity });
      });
    }
  });
});
// 短信
const crypto = require("crypto");
function md5(content) {
  const md5 = crypto.createHash("md5");
  return md5.update(content).digest("hex");
}
router.post("/sendMessage", (req, res) => {
  // return
  const https = require("https");
  const querystring = require("node:querystring");
  var content = "";
  var apikey = "";
  var secret = "";
  var mobile = "";
  var sign_id = "";
  // 通知短信
  if (req.body.pass == "notice") {
    var code = "";
    apikey = "N557098755";
    secret = "55709dba6a8eef83";
    mobile = req.body.mobile;
    sign_id = "130014";
    // content = req.body.content;
    for (let i = 0; i < 6; i++) {
      // const text = Math.round(Math.random() * arr.length - 1);
      // this.scJzm += arr[text];
      // console.log(Math.round(Math.random() * 9));
      code += Math.round(Math.random() * 9);
    }
    content =
      "验证码为：" + code + "，5分钟内有效，若非本人操作，请忽略此短信。";
  } else {
    // console.log(req.body);
    if (req.body.sign_id == "" || req.body.sign_id == undefined) {
      return res.json({ status: -10, msg: "尚未授权短信发送，请联系管理员" });
    } else {
      apikey = "M55709da2f";
      secret = "557093936b06054e";
      mobile = req.body.mobile;
      content = req.body.content + " 拒收请回复R";
      sign_id = req.body.sign_id;
    }
  }

  // return res.json({ status: 1 });
  let _id = objectId(req.body._id);
  // return;
  var postData = {
    mobile,
    content,
    apikey,
    secret,
    sign_id,
  };
  // console.log(postData);
  // return
  var Date = querystring.stringify(postData);
  var options = {
    host: "api.4321.sh",
    path: "/sms/send",
    method: "POST",
    agent: false,
    rejectUnauthorized: false, //证书验证
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Content-Length": Date.length,
    },
  };

  var req = https.request(options, function (res_) {
    // console.log(options);
    res_.setEncoding("utf8");
    res_.on("data", function (chunk) {
      // console.log(chunk);
      // console.log(code);

      // const state = JSON.parse(chunk).code;
      // return;
      if (code != undefined) {
        return res.json({ status: 1, code: md5(md5(code)) });
      } else {
        getDb((err, db) => {
          const dbo = sDb(db, "HJSYS");
          if (err) {
            return res.json({ status: -20, msg: "数据库连接失败" });
          } else {
            dbo.collection("UAdmin").findOne({ _id }, (error, result) => {
              // console.log(result);
              if (Number(result.messagesQuantity) <= 0) {
                return { status: -9, msg: "发送失败，请充值短信！" };
              } else {
                dbo.collection("UAdmin").updateOne(
                  { _id },
                  {
                    $set: {
                      messagesQuantity: Number(result.messagesQuantity) - 1,
                    },
                  },
                  (err, res_) => {
                    // return res_mess
                    // console.log(err);
                  }
                );
              }
              // res_mess = Number(result.messagesQuantity) - 1;
              // console.log(messagesQuantity);
            });
          }
        });
        return res.json({
          status: 1,
          data: JSON.parse(chunk),
        });
      }
    });
    res_.on("end", function () {
      console.log("over");
    });
  });

  req.write(Date);
  req.end();
});
router.post("/clearbx", (req, res) => {
  let EStoreName = req.body.LoginInfo;
  getDb((err, db) => {
    const dbo = sDb(db, "HJSYS");
    if (err) {
      return res.json({ status: -20, msg: "数据库连接失败" });
    } else {
      dbo
        .collection(EStoreName)
        // .find({ bx_true: true }, { bx_true: true })
        .find({ $or: [{ bx_true: "true" }, { bx_true: true }] })
        .forEach((item) => {
          dbo
            .collection(EStoreName)
            // .update({ bx_true: true }, { $set: { bx_true: false } });
            .updateMany(
              { $or: [{ bx_true: "true" }, { bx_true: true }] },
              { $set: { bx_true: false } }
            );
        });
    }
  });
});
// 清除审车信息
router.post("/clearsc", (req, res) => {
  let EStoreName = req.body.LoginInfo;
  getDb((err, db) => {
    getDb((err, db) => {
      const dbo = sDb(db, "HJSYS");
      if (err) {
        return res.json({ status: -20, msg: "数据库连接失败" });
      } else {
        dbo
          .collection(EStoreName)
          .find({ $or: [{ sc_true: "true" }, { sc_true: true }] })
          .forEach((item) => {
            dbo
              .collection(EStoreName)
              .updateMany(
                { $or: [{ sc_true: "true" }, { sc_true: true }] },
                { $set: { sc_true: false } }
              );
          });
      }
    });
  });
});
module.exports = router;
